package cn.sciento.core.jackson.deserializer;

import cn.sciento.core.jackson.annotation.Trim;
import cn.sciento.core.util.TrimUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.deser.std.StringDeserializer;

import java.io.IOException;

public class TrimStringDeserializer extends JsonDeserializer<String> implements ContextualDeserializer {
    private Trim trim;

    public TrimStringDeserializer setTrim(Trim trim) {
        this.trim = trim;
        return this;
    }

    public String deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
        return TrimUtils.trim(this.trim, jsonParser.getValueAsString());
    }

    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
        if (property != null && property.getMember() != null && property.getMember().hasAnnotation(Trim.class))
            return (new TrimStringDeserializer()).setTrim((Trim) property.getMember().getAnnotation(Trim.class));
        return (JsonDeserializer<?>) new StringDeserializer();
    }
}
